import { createRouter, createWebHashHistory } from 'vue-router'
import { useUserStore } from '../store/UserStore'

// 管理员后台页面组件
import AdminHome from '../components/admin_View/Admin_Home.vue'
import AdminIndex from '../components/admin_View/AdminIndex.vue'
import AdminFeedbackLayout from '../components/admin_View/AdminFeedbackLayout.vue'
import FeedbackExperience from '../components/admin_View/Admin_feedback_Response/FeedbackExperience.vue'
import FeedbackQuestion from '../components/admin_View/Admin_feedback_Response/FeedbackQuestion.vue'
import AdminFeedback from '../components/admin_View/Admin_feedback_Response/Admin_feedback.vue'
import AdminLogs from '../components/admin_View/Admin_Logs.vue'
import AdminInfo from '../components/admin_View/Admin_Info.vue'
import UserInfoAdmin from '../components/admin_View/User_Info_Admin.vue'
import UserInfoAdminView from '../components/admin_View/User_Info_AdminView.vue'
import Login from './Login.vue'
import AdminDiscussionTopic from '../components/admin_View/Admin_discussiontopic.vue'
import SysLog from '../components/admin_View/SysLog.vue'
// 引入 Set.vue
import Set from './Set.vue' 
// 引入 ForgetPassword.vue
import ForgetPassword from './ForgetPassword.vue' 



const routes = [
  { 
    path: '/', 
    redirect: '/login'
  },
  { 
    path: '/login', 
    name: 'login',
    component: Login 
  },
  // 新增 Set.vue 路由配置
    { 
      path: '/register', 
      name: 'register',
      component: Set 
    },
    // 新增 ForgetPassword.vue 路由配置
    { 
      path: '/forget-password', 
      name: 'forget-password',
      component: ForgetPassword 
    },
  // ✅ 用户主页面：顶层路由，不属于管理员
  {
    path: '/home',
    name: 'UserHome',
    component: () => import('../components/user_View/User_Home.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        path: 'user-center',
        name: 'UserCenter',
        component: () => import('../components/user_View/user_center/User_center_index.vue'),
        children: [
          {
            path: '',
            name: 'UserCenterOverview',
            component: () => import('../components/user_View/user_center/User_overview.vue')
          },
          {
            path: 'favorites',
            name: 'UserCenterFavorites',
            component: () => import('../components/user_View/user_center/User_favorites.vue')
          },
          {
            path: 'progress',
            name: 'UserCenterProgress',
            component: () => import('../components/user_View/user_center/User_progress_schedule.vue')
          },
          {
            path: 'test',
            name: 'UserCenterTest',
            component: () => import('../components/user_View/user_center/User_test_record.vue')
          },
          {
            path: 'message',
            name: 'UserCenterMessage',
            component: () => import('../components/user_View/user_center/User_message.vue')
          },
          {
            path: 'feedback',
            name: 'UserCenterFeedback',
            component: () => import('../components/user_View/user_center/User_feedback.vue')
          },
          {
            path: 'setting',
            name: 'UserCenterSetting',
            component: () => import('../components/user_View/user_center/Userinfo_setting.vue')
          }
        ]
      },
      {
  path: '/home/learning',
  name: 'UserLearning',
  component: () => import('../components/user_View/UserLearning/StudyHome.vue')
},
{
  path: '/home/learning/learn',
  name: 'Learn408',
  component: () => import('../components/user_View/UserLearning/408_Learn.vue')
},
{
  path: '/home/learning/practice',
  name: 'Practice408',
  component: () => import('../components/user_View/UserLearning/408_Practice.vue')
},
{
  path: '/home/ExamPagehome',
  name: 'ExamPageHome',
  component: () => import('../components/user_View/UserTesting/ExamPagehome.vue')
},
{
  path: '/home/ExamPagetesting',
  name: 'ExamPageTesting',
  component: () => import('../components/user_View/UserTesting/ExamPagetesting.vue')
},
{
  path: '/home/ExamPageanswer',
  name: 'ExamPageAnswer',
  component: () => import('../components/user_View/UserTesting/ExamPageanswer.vue')
},
  {
    path: '/home/learning/knowledge-points',
    name: 'KnowledgePointSelection',
    component: () => import('../components/user_View/UserLearning/KnowledgePointSelection.vue'),
    meta: {
      title: '知识点选择',
      requiresAuth: true
    }
  },
      {
        path: 'user-communication',
        name: 'UserCommunication',
        component: () => import('../components/user_View/user_communication/User_communication.vue')
      },
      {
        path: 'my-discussion',
        name: 'MyDiscussion',
        component: () => import('../components/user_View/user_communication/my_discussion.vue')
      },
     {
        path: '/user/communication/post',
        name: 'UserCommunicationPost',
        component: () => import('../components/user_View/user_communication/User_communicationpost.vue')
      },
      {
        path: 'wrong-questions',
        name: 'WrongQuestions',
        component: () => import('../components/user_View/Repractice_mistakes/MistakesReview.vue')
      },
      {
        path: 'ai-progress-analysis',
        name: 'AiProgressAnalysis',
        component: () => import('../components/user_View/ai_assistant/Ai_progress_analysis.vue')
      },
      {
      path: 'practice-mistakes',
      name: 'PracticeMistakes',
      component: () => import('../components/user_View/Repractice_mistakes/PracticeMistakes.vue')
    },
    {
      path: 'favorite-questions',
      name: 'FavoriteQuestion',
      component: () => import('../components/user_View/Repractice_mistakes/FavoriteQuestion.vue')
    },
    {
      path: 'favorite-question-practice',
      name: 'FavoriteQuestionPractice',
      component: () => import('../components/user_View/Repractice_mistakes/FavoriteQuestionPractice.vue')
    }
    ]
  },
  // 管理员后台页面组件
  {
    path: '/admin',
    component: AdminHome,
    meta: { requiresAuth: true, requiresAdmin: true },
    children: [
      { 
        path: '', 
        redirect: { name: 'AdminIndex' }
      },
      {
        path: 'dashboard',
        name: 'AdminIndex',
        component: AdminIndex
      },
      {
        path: 'feedback',
        name: 'AdminFeedback',
        component: AdminFeedbackLayout,
        children: [
          { 
            path: '', 
            name: 'admin-feedback-default',
            redirect: { name: 'admin-feedback-experience' } 
          },
          { 
            path: 'experience', 
            name: 'admin-feedback-experience', 
            component: FeedbackExperience 
          },
          { 
            path: 'question', 
            name: 'admin-feedback-question', 
            component: FeedbackQuestion 
          },
          {
            path: 'responses',
            name: 'admin-feedback-responses',
            component: AdminFeedback
          }
        ]
      },
      { 
        path: 'questions', 
        name: 'admin-questions', 
        component: () => import('../components/admin_View/question_main_page.vue')
      },
      { 
        path: 'users', 
        name: 'admin-users', 
        component: UserInfoAdmin 
      },
      { 
        path: 'users/:userId', 
        name: 'admin-user-profile', 
        component: UserInfoAdminView,
        props: true,
        meta: { 
          title: '用户画像',
          requiresAuth: true 
        }
      },
      { 
        path: 'logs', 
        name: 'admin-logs', 
        component: AdminLogs 
      },
      { 
        path: 'profile', 
        name: 'admin-profile', 
        component: AdminInfo 
      },
      {
        path: 'discussion-topics',
        name: 'admin-discussion-topics',
        component: AdminDiscussionTopic
      },
      {
        path: 'system-logs',
        name: 'admin-system-logs',
        component: SysLog 
      }
    ]
  },
  { 
    path: '/:pathMatch(.*)*', 
    redirect: '/login' 
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore();
  


  let isLoggedIn = userStore.getIsLoggedIn
  let isAdmin = userStore.isAdmin

  // 兜底：如果 pinia 还没恢复，但 localStorage 里有
  if (!isLoggedIn && localStorage.getItem('user')) {
    // 这里的 userData 是整个 userStore 的 state
    const userData = JSON.parse(localStorage.getItem('user'))
    isLoggedIn = userData.isLoggedIn
    isAdmin = userData.role === 'admin'
    // 同步到 pinia
    userStore.isLoggedIn = isLoggedIn
    userStore.role = userData.role
    userStore.token = userData.token
    userStore.userInfo = userData.userInfo
    userStore.avatarUrl = userData.avatarUrl
  }
  
  // 如果需要登录
  if (to.meta.requiresAuth) {
    if (!isLoggedIn) {
      // 未登录，重定向到登录页
      next('/login')
      return
    }

    // 如果需要管理员权限
    if (to.meta.requiresAdmin && !isAdmin) {
      // 不是管理员，重定向到用户首页
      next('/home')
      return
    }
  }

  // 如果已登录且访问登录页
  if (to.path === '/login' && isLoggedIn) {
    // 根据角色重定向
    if (isAdmin) {
      next('/admin')
    } else {
      next('/home')
    }
    return
  }

  // 其他情况正常放行
  next()
})

export default router